import { get as getVal, writable, type Writable } from "svelte/store";
import { object, string, number, type Asserts, boolean } from 'yup';
import type { EntityTypeSpec } from "./type";


type Category = {
  id: number;
  name: string;
  pid?: number | null;
  sort_no: number;
  leaf_flag: boolean;
};

export const defaults = () => {
  return {id: undefined, name: "", pid: null, sort_no:1, leaf_flag: true }
}

export type CreateCategoryResponse = {
  created: Category;
  categories: Category[];
}
export type UpdateCategoryResponse = {
  updated: Category;
  categories: Category[];
}

export type DeleteCategoryResponse = {
  deleted: Category;
  categories: Category[];
}

export const CategoryEntityPropertySpec: EntityTypeSpec<Category> = {
  id: { key: "id", name: "分类id", type: "number", width: 64 },
  name: { key: "name", name: "分类名称", type: "string" },
  pid: { key: "pid", name: "父分类id", type: "number" },
  sort_no: { key: "sort_no", name: "序号", type: "number" },
  leaf_flag: { key: "leaf_flag", name: "叶子标记", type: "boolean" },
};

export const AppCategoryAsListItemAllKeys = ['id', 'name'] as const;
type AppCategoryAsListItemKeysTuple = typeof AppCategoryAsListItemAllKeys;
type AppCategoryAsListItemKeys = AppCategoryAsListItemKeysTuple[number];
export type AppCategoryAsListItem = Pick<Category, AppCategoryAsListItemKeys>;

export const AppCategorySchema = object({
  id: string().required("分类id必填"),
  name: string().required("分类名称必填").max(32, "最多16个字"),
  pid: number().optional().min(0, "不能<0"),
  sort_no: number().required("排序序号必填"),
  leaf_flag: boolean().default(true),
})

export const CreateAppCategorySchema = AppCategorySchema.omit(["id", "sort_no", "leaf_flag"]);
export const UpdateAppCategorySchema = AppCategorySchema.omit(["id", "leaf_flag"]);

type AppCategoryMap = {
  [k: string]: Writable<Category[]>;
};

const appCategoriesMap: AppCategoryMap = {};

export const setAppCategorySubscribe = (app_id: string, o: Category[]) => {
  if (!appCategoriesMap[app_id]) {
    appCategoriesMap[app_id] = writable(o);
  }
  appCategoriesMap[app_id].set(o);
};

export const getAppCategorySubscribe = (app_id: string) => {
  let v = appCategoriesMap[app_id];
  if (!v) {
    appCategoriesMap[app_id] = v = writable();
  }
  console.log('appCategoriesMap[app_id]=>', v)
  return v;
};

export const hasAppCategorySubscribe = (app_id: string) => {
  return !!appCategoriesMap[app_id];
};

export default Category;
